import useUserStore from '@/stores/modules/user'
import usePermissionStore from '@/stores/modules/permission'
import router from '..'

const whiteRoutes: string[] = ['/login', '/exception/404', '/exception/403', '/exception/500']

function usePermissionGuard() {

    router.beforeEach(async (to) => {
        console.log(router.getRoutes())
        if (whiteRoutes.includes(to.path)) {
            return true
        }
        const userStore = useUserStore()
        if (userStore.isTokenExpire()) {
            return {
                path: '/login',
                query: { redirect: to.fullPath },
            }
        }

        const permissionStore = usePermissionStore()
        const isEmptyRoute = permissionStore.isEmptyPermissionRoute()
        if (isEmptyRoute) {
            await permissionStore.initPermissionRoute()
            return { ...to, replace: true }
        }
        return true
    })
}

export default usePermissionGuard
